#include "Map.h"
#include "MapCanvas.h"
#include "MapRenderer.h"
#include <QPainter>


namespace TGS{
namespace MapControl{


Map::Map()
	: _useQImageToRender(true)
	, _mapRenderer(new MapRenderer())
{
	setZValue( -10 );
	setPos( 0, 0 );
	resize( QSize( 1, 1 ) );
	_useQImageToRender = true;
}

Map::~Map()
{
	if(_mapRenderer)
	{
		delete _mapRenderer;
		_mapRenderer = nullptr;
	}
}

void Map::resize( QSize size )
{
	prepareGeometryChange();

	_pixmap = QPixmap( size );
	_pixmap.fill( _bgColor.rgb() );
	// temporary image - build it here so it is available when 
	// switching from QPixmap to QImage rendering
	_image = QImage( size, QImage::Format_RGB32 ); 
	_mapRenderer->setOutputSize( size, _pixmap.logicalDpiX() );
}

void Map::setPanningOffset( const QPoint& point )
{
	_offset = point;
	 setPos( _offset );
}

void Map::render()
{
	if ( _useQImageToRender )
	{
		// use temporary image for rendering
		_image.fill( _bgColor.rgb() );

		// clear the pixmap so that old map won't be displayed while rendering
		// TODO: do the canvas updates wisely -> this wouldn't be needed
		_pixmap = QPixmap( _image.size() );
		_pixmap.fill( _bgColor.rgb() );

		QPainter paint;
		paint.begin( &_image );
		// Clip drawing to the QImage
		paint.setClipRect( _image.rect() );

		// antialiasing
		if ( _antiAliasing ) paint.setRenderHint( QPainter::Antialiasing );

		_mapRenderer->render( &paint );

		paint.end();

		// convert QImage to QPixmap to acheive faster drawing on screen
		_pixmap = QPixmap::fromImage( _image );
	}
	else
	{
		_pixmap.fill( _bgColor.rgb() );
		QPainter paint;
		paint.begin( &_pixmap );
		// Clip our drawing to the QPixmap
		paint.setClipRect( _pixmap.rect() );
		// antialiasing
		if ( _antiAliasing ) paint.setRenderHint( QPainter::Antialiasing );

		_mapRenderer->render( &paint );
		paint.end();
	}

	update();
}

QPaintDevice& Map::paintDevice()
{
	return _pixmap;
}

void Map::updateContents()
{
	// make sure we're using current contents
	if ( _useQImageToRender )
		_pixmap = QPixmap::fromImage( _image );

	update();
}

void Map::paint( QPainter* p, const QStyleOptionGraphicsItem*, QWidget* )
{
	p->drawPixmap( 0, 0, _pixmap );
}

QRectF Map::boundingRect() const
{
	return QRectF( 0, 0, _pixmap.width(), _pixmap.height() );
}

RenderContext* Map::renderContext()
{
	return _mapRenderer->renderContext();
}

void Map::clearRenderers()
{
	_mapRenderer->clearRenderers();
}

}//MapControl
}//TGS